package com.xbts.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.xbts.common.annotation.DataScope;
import com.xbts.common.constant.UserConstants;
import com.xbts.common.core.domain.AjaxResult;
import com.xbts.common.core.domain.CnWalletLog;
import com.xbts.common.core.domain.Setting;
import com.xbts.common.core.domain.entity.SysRole;
import com.xbts.common.core.domain.entity.SysUser;
import com.xbts.common.enums.SettingEnum;
import com.xbts.common.enums.ShoppingCarEnums;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.SecurityUtils;
import com.xbts.common.utils.StringUtils;
import com.xbts.common.utils.bean.BeanUtils;
import com.xbts.common.utils.bean.BeanValidators;
import com.xbts.common.utils.http.HttpUtils;
import com.xbts.common.utils.spring.SpringUtils;
import com.xbts.system.domain.SysPost;
import com.xbts.system.domain.SysUserAuthentication;
import com.xbts.system.domain.SysUserPost;
import com.xbts.system.domain.SysUserRole;
import com.xbts.system.domain.vo.SysUserControlVO;
import com.xbts.system.mapper.*;
import com.xbts.system.module.payment.enums.PaymentMethodEnum;
import com.xbts.system.module.payment.mapper.CnWalletLogMapper;
import com.xbts.system.module.payment.service.ICnWalletLogService;
import com.xbts.system.service.ISysConfigService;
import com.xbts.system.service.ISysUserAuthenticationService;
import com.xbts.system.service.ISysUserService;
import com.xbts.system.service.SettingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author xbts
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    protected Validator validator;

    @Autowired
    protected CnUserCloudServersRelationMapper userCloudServersRelationMapper;

    @Autowired
    private ISysUserAuthenticationService sysUserAuthenticationService;

    @Autowired
    private SettingService settingService;

    @Autowired
    private ICnWalletLogService walletLogService;
    @Autowired
    private CnWalletLogMapper walletLogMapper;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    @Override
    public SysUser selectUserByPhonenumber(String phonenumber) {
        return userMapper.selectUserByPhonenumber(phonenumber);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Transactional
    @Override
    public boolean registerUser(SysUser user) {
        String userType = user.getUserType();
        if(StringUtils.isNull(user.getAuthentication())) {
            if(StringUtils.equals(UserConstants.USER_TYPE_COMPANY, userType)) {
                // 认证中
                user.setAuthentication(UserConstants.AUTHENTICATING);
            } else {
                user.setAuthentication(UserConstants.UNAUTHENTICATED);
            }
        }
        userMapper.insertUser(user);


        // 创建认证审核
        SysUserAuthentication sysUserAuthentication = new SysUserAuthentication();
        BeanUtils.copyProperties(user, sysUserAuthentication);
        sysUserAuthentication.setStatus(1);
        sysUserAuthentication.setUserId(user.getUserId().toString());
        sysUserAuthentication.setCreateTime(new Date());
        if (StringUtils.equals(UserConstants.USER_TYPE_COMPANY, userType)){
            sysUserAuthentication.setType(2);
        } else {
            sysUserAuthentication.setType(1);
        }
        sysUserAuthenticationService.save(sysUserAuthentication);

        // 设置基础角色
        List<SysUserRole> list = new ArrayList<>();
        SysUserRole ur = new SysUserRole();
        ur.setUserId(user.getUserId());
        ur.setRoleId(2L);
        list.add(ur);
        userRoleMapper.batchUserRole(list);

        return  true;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<SysUser> realNameVerificationList(SysUser sysUser) {
        return userMapper.realNameVerificationList(sysUser);
    }

    @Override
    public AjaxResult audit(SysUser sysUser) {
        if (null == sysUser.getAuthentication()) {
            return AjaxResult.error("认证状态不能为空");
        }
        SysUser dbUser = userMapper.selectUserById(sysUser.getUserId());

        if (dbUser.getUserType().equals(UserConstants.USER_TYPE_USER_TO_COMPANY)) {
            // 个人认证为企业认证 认证成功将用户类型改为企业用户
            if (UserConstants.AUTHENTICATED.equals(sysUser.getAuthentication())) {
                sysUser.setUserType(UserConstants.USER_TYPE_COMPANY);
            }
            // 个人认证为企业认证 认证成功将用户类型改为普通用户
            if (UserConstants.AUTHENTICATED_FAIL.equals(sysUser.getAuthentication())) {
                sysUser.setUserType(UserConstants.USER_TYPE_USER);
            }
        }
        return userMapper.updateUser(sysUser) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public AjaxResult realNameVerification(SysUser sysUser) {
        // TODO 个人认证为企业认证 user_type 前端传 03
        if (StringUtils.isEmpty(sysUser.getUserType())) {
            return AjaxResult.error("用户类型不能为空");
        }
        if (null == sysUser.getUserId()) {
            return AjaxResult.error("用户id不能为空");
        }
        if (StringUtils.isEmpty(sysUser.getNumber())) {
            return AjaxResult.error("身份证号码/社会统一信用代码不能为空");
        }
        if (UserConstants.USER_TYPE_USER.equals(sysUser.getUserType()) && StringUtils.isEmpty(sysUser.getRealName())) {
            return AjaxResult.error("真实姓名不能为空");
        }
        if (StringUtils.isEmpty(sysUser.getCertificatePath())) {
            return AjaxResult.error("证件照不能为空");
        }
        sysUser.setAuthentication(UserConstants.UNAUTHENTICATED);
        return userMapper.updateUser(sysUser) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public AjaxResult wechatBind(SysUser sysUser) {
        if (StringUtils.isEmpty(sysUser.getWechatOpenId())) {
            return AjaxResult.error("微信openId不能为空");
        }
        SysUser user = userMapper.selectUserByUserName(sysUser.getUserName());
        if(StringUtils.isNull(user)){
            return AjaxResult.error("用户不存在！");
        }
        boolean b = SecurityUtils.matchesPassword(sysUser.getPassword(), user.getPassword());
        if(!b){
            return AjaxResult.error("密码不正确！");
        }
        user.setWechatOpenId(sysUser.getWechatOpenId());
        return userMapper.updateUser(user) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public AjaxResult wechatUnBind(SysUser sysUser) {
        if (null == sysUser.getUserId()) {
            return AjaxResult.error("用户id不能为空");
        }
        return userMapper.wechatUnBind(sysUser) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<SysUser> managerUser() {
        return userMapper.selectUserByUserType("00");
    }

    @Override
    public List<SysUser> memberList() {
        return userMapper.selectMemberList();
    }

    @Override
    public BigDecimal selectUserBalance() {
        if(null == SecurityUtils.getUserId()){
            throw new ServiceException("用户未登录");
        }
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(SysUser::getUserWallet);
        lambdaQueryWrapper.eq(SysUser::getUserId, userId);
        SysUser sysUser = getOne(lambdaQueryWrapper);
        if (null == sysUser) {
            return BigDecimal.ZERO;
        }
        return sysUser.getUserWallet() == null ? BigDecimal.ZERO : sysUser.getUserWallet();
    }

    @Override
    public SysUserControlVO getUserInfo(Long userId) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 只查询SysUser中所有的字段
        lambdaQueryWrapper.select(SysUser::getUserId, SysUser::getUserName, SysUser::getNickName, SysUser::getPhonenumber,
                SysUser::getEmail, SysUser::getSex, SysUser::getAvatar, SysUser::getStatus, SysUser::getDelFlag,
                SysUser::getLoginIp, SysUser::getLoginDate, SysUser::getCreateBy, SysUser::getCreateTime, SysUser::getUpdateBy,
                SysUser::getUpdateTime, SysUser::getAuthentication,SysUser::getRealName, SysUser::getNumber,
                SysUser::getCertificatePath, SysUser::getWechatOpenId, SysUser::getUserType, SysUser::getUserWallet);
        lambdaQueryWrapper.eq(SysUser::getUserId, userId);
        SysUser sysUser = getOne(lambdaQueryWrapper);
        SysUserControlVO sysUserControlVO = new SysUserControlVO();
        if (null != sysUser){
            BeanUtils.copyProperties(sysUser, sysUserControlVO);
            // 查询用户服务器数量
            List<Map> maps = userCloudServersRelationMapper.selectUserServiceCount(userId);
            if (null != maps && maps.size() > 0){
                // list转map
                Map<String, Integer> map = maps.stream()
                        .collect(Collectors.toMap(
                                m -> m.get("shopping_car_enums").toString(),
                                m -> Integer.parseInt(m.get("count").toString())
                        ));
                sysUserControlVO.setCloudServerNum(map.getOrDefault(ShoppingCarEnums.CLOUD_SERVER.name(), 0));
                sysUserControlVO.setCloudMarketNum(map.getOrDefault(ShoppingCarEnums.CLOUD_MARKET.name(), 0));
                sysUserControlVO.setGovCloudNum(map.getOrDefault(ShoppingCarEnums.GOV_CLOUD.name(), 0));
            }
        }
        return sysUserControlVO;
    }

    @Override
    public AjaxResult wechatBindCheck(String code) {
        JSONObject connect = getConnect(code);
        String openId = connect.getString("openid");
        System.out.println("openid-------" + openId);
        System.out.println("connect-------" + connect);
        if(StringUtils.isBlank(openId)){
            throw new ServiceException("code过期");
        }
        Integer integer = userMapper.wechatBindCheck(openId);
        if(integer > 0){
            return AjaxResult.success("操作成功！", null);
        }
        return AjaxResult.success("操作成功！", openId);
    }

    @Transactional
    @Override
    public synchronized int editWallet(String type, CnWalletLog cnWalletlog) {
        Long userId = cnWalletlog.getUserId();
        if (null == userId){
            throw new ServiceException("用户id不能为空！");
        }
        SysUser user = userMapper.selectUserById(userId);
        BigDecimal userWallet = user.getUserWallet();
        BigDecimal money = cnWalletlog.getMoney();
        if (null == money){
            throw new ServiceException("金额不能为空！");
        }
        String sn = cnWalletlog.getSn();
        if(StringUtils.isBlank(sn)){
            throw new ServiceException("支付编码不能为空！");
        }
        cnWalletlog.setNickName(user.getNickName());
        if("increase".equals(type)){
            cnWalletlog.setPaymentMethod(PaymentMethodEnum.PLATFORM_INCREASE.name());
        } else if("decrease".equals(type)){
            cnWalletlog.setPaymentMethod(PaymentMethodEnum.PLATFORM_DECREASE.name());
            if(userWallet.compareTo(money) < 0){
                throw new ServiceException("余额不足！");
            }
            String productTypeName = cnWalletlog.getProductTypeName();
            if(StringUtils.isBlank(productTypeName)){
                throw new ServiceException("产品类型不能为空！");
            }
            String term = cnWalletlog.getTerm();
            if(StringUtils.isBlank(term)){
                throw new ServiceException("产品和产品数量及期限不能为空！");
            }
            cnWalletlog.setMoney(money.negate());
        }
        userWallet = userWallet.add(cnWalletlog.getMoney());
        walletLogMapper.updateUserBalance(userId, userWallet);
        return walletLogService.save(cnWalletlog) ? 1 : 0;
    }

    @Override
    public List<SysUser> walletList(SysUser sysUser) {
        return userMapper.selectWalletList(sysUser);
    }

    @Override
    public String getEmailByUserId(Long userId) {
        return userMapper.getEmailByUserId(userId);
    }

    /**
     * 通过微信返回等code 获取openid 等信息
     *
     * @param code 微信code
     * @return 微信返回的信息
     */
    public JSONObject getConnect(String code) {
        Setting setting = settingService.get(SettingEnum.WECHAT_PUBLIC_PLATFORM_SETTING.name());
        String settingValue = setting.getSettingValue();
        JSONObject jsonObject = JSONObject.parseObject(settingValue);
        if (null == jsonObject){
            throw new ServiceException("未配置微信公众号信息，请联系管理员！");
        }
        String appid = (String)jsonObject.get("appid");
        String secret = (String)jsonObject.get("secret");

        // 公众号获取openId https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appid + "&" +
                "secret=" + secret + "&" +
                "code=" + code + "&" +
                "grant_type=authorization_code";
        String content = HttpUtils.doGet(url, "UTF-8", 100, 1000);

        return JSON.parseObject(content);
    }
}
